/* 几何变换算法库
 *
 * geometric transformation
 *
 * gm_translation: 平移
 * 
 *
 *
 * */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "raylib.h"
#include "pub_lib.h"

//int pix_len; default is 3，每个像素占几个字节

/*
 *  line_bytes: 一行的像素一共有多少字节
 *  从原始图像的缓存中得到索引值
 * */
static int get_index(int row, int col, int line_bytes, int pix_len)
{
	int index = row * line_bytes + col * pix_len;
	return index;
}

void gm_translation(Image *ori, Image *chg, int pix_len, int x_offset, int y_offset)
{
	int i, j, newx, newy;
	int line_size;
	int index, new_index;
	char* src, * dst;
	int image_size;

	line_size = ori->width * pix_len;
	image_size = ori->height * line_size;
	dst = (char*)chg->data;
	src = (char*)ori->data;
	memset(dst, 255, image_size);

	for (i = 0; i < ori->width; i++) {
		for (j = 0; j < ori->height; j++) {
			index = get_index(i, j, line_size, pix_len);
			newx = i + y_offset;
			newy = j + x_offset;
			if (newx <= 0 || newx >= ori->width)
				continue;
			if (newy <= 0 || newy >= ori->height)
				continue;
			new_index = get_index(newx, newy, line_size, pix_len);

			if (new_index >= image_size)
				continue;
			dst[new_index] = src[index];
			dst[new_index+1] = src[index+1];
			dst[new_index+2] = src[index+2];
		}
	}
}

/* is_hon = 1, horizaontal, 水平镜像
 * otherwise, vertical，垂足镜像 */
void gm_mirror(Image *ori, Image *chg, int pix_len, int is_hon)
{
	int line_size, image_size;
	char *dst, *src;

	line_size = ori->width * pix_len;
	image_size = ori->height * line_size;
	dst = (char*)chg->data;
	src = (char*)ori->data;

	int i, j, index, new_index;
	for (i = 0; i < ori->width; i++) {
		for (j = 0; j < ori->height; j++) {
			index = get_index(i, j, line_size, pix_len);
			if(is_hon)
				new_index = get_index(i, ori->width - j - 1, line_size, pix_len);
			else
				new_index = get_index(ori->height - i - 1, j, line_size, pix_len);
			dst[new_index] = src[index];
			dst[new_index+1] = src[index+1];
			dst[new_index+2] = src[index+2];
		} //end for
	} //end for
}

/* 图像转置 , x, y 互换， 图像宽高互换  */
void gm_transpose(Image *ori, Image *chg, int pix_len)
{
	int line_size, image_size;
	char *dst, *src;

	line_size = ori->width * pix_len;
	image_size = ori->height * line_size;
	dst = (char*)chg->data;
	src = (char*)ori->data;

	int i, j, index, new_index;
	for (i = 0; i < ori->width; i++) {
		for (j = 0; j < ori->height; j++) {
			index = get_index(i, j, line_size, pix_len);
			new_index = get_index(j, i, line_size, pix_len);
			dst[new_index] = src[index];
			dst[new_index+1] = src[index+1];
			dst[new_index+2] = src[index+2];
		} //end for
	} //end for


}

